package com.dnjn.happiness.system.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.config.DateTimeFormatHolder;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.TeamVo;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.common.security.utils.VerifyUtil;
import com.dnjn.happiness.system.api.domain.SysTeam;
import com.dnjn.happiness.system.domain.vo.ExportTeamVO;
import com.dnjn.happiness.system.domain.vo.SysTeamVO;
import com.dnjn.happiness.system.service.ISysTeamService;
import com.dnjn.happiness.system.util.TreeXmindlUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xmind.core.CoreException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 人员架构Controller
 * 
 * @author amber
 * @date 2024-01-02
 */
@Tag(name = "sys sysTeam 人员架构", description = "人员架构")
@RestController
@RequestMapping("/admin/sysTeam")
public class AdminSysTeamController extends BaseController
{
    @Autowired
    private ISysTeamService sysTeamService;

    /**
     * @
     */
    @InnerAuth
    @GetMapping("/updateAppraiseTime/{userId}")
    public void updateAppraiseTime(@PathVariable Long userId){
        sysTeamService.updateAppraiseTime(userId);
    }

    /**
     * @return
     */
    @InnerAuth
    @GetMapping("/getChildList/{teamId}")
    public R<List<Long>> getChildList(@PathVariable Long teamId){
        List<SysTeam> list = new ArrayList<>();
        sysTeamService.getChildList1(teamId,list);
        List<Long> collect = list.stream().map(SysTeam::getUserId).collect(Collectors.toList());
        return R.ok(collect);
    }

    /**
     * @return
     */
    @InnerAuth
    @PutMapping("/updateTeamCheckTimeByUserId/{userId}")
    public void updateTeamCheckTimeByUserId(@PathVariable Long userId){
        sysTeamService.lambdaUpdate().eq(SysTeam::getDeleted, '0')
                .eq(SysTeam::getUserId, userId).set(SysTeam::getCheckTime, LocalDateTime.now()).update();
    }

    /**
     * @return
     */
    @InnerAuth
    @GetMapping("/getMangerUpOne/{userId}")
    public R<SysTeam> getMangerUpOne(@PathVariable Long userId){
        return R.ok(sysTeamService.getMangerUpOne(userId));
    }

    /**
     * @return
     */
    @InnerAuth
    @GetMapping("/getSubordinate/{userId}")
    public R<List<SysTeam>> getSubordinate(@PathVariable Long userId){
        return R.ok(sysTeamService.getSubordinate(userId));
    }

    /**
     * @return
     */
    @InnerAuth
    @GetMapping("/getManager/{userId}")
    public R<List<SysTeam>> getManager(@PathVariable Long userId){
        return R.ok(sysTeamService.getManager(userId));
    }

    /**
     * @return
     */
    @InnerAuth
    @PostMapping("/getLeaderList")
    public R<List<SysTeam>> getLeaderList(@RequestBody List<SysTeam> sysTeams){
        return R.ok(sysTeamService.getLeaderList(sysTeams));
    }

    /**
     * @return
     */
    @InnerAuth
    @PostMapping("/getEmployees")
    public R<List<SysTeam>> getEmployees(@RequestBody List<SysTeam> sysTeams){
        return R.ok(sysTeamService.getEmployees(sysTeams));
    }

    /**
     * @param deptId
     * @return
     */
    @InnerAuth
    @GetMapping("/getLeaderListBydeptId/{deptId}")
    public R<List<SysTeam>> getLeaderListBydeptId(@PathVariable Long deptId){
        return R.ok(sysTeamService.getLeaderListBydeptId(deptId));
    }

    /**
     * @param userId
     * @return
     */
    @InnerAuth
    @GetMapping("/getParentInfoByUserId/{userId}")
    public R<SysTeam> getParentInfoByUserId(@PathVariable Long userId){
        return R.ok(sysTeamService.getParentInfoByUserId(userId));
    }

    /**
     * 根据userId查询team
     * @param userId
     * @return
     */
    @InnerAuth
    @GetMapping("/getInfoById/{userId}")
    public R<SysTeam> getInfoById(@PathVariable Long userId){
        SysTeam team = sysTeamService.getTeamByUserId(userId);
        return R.ok(team);
    }

    /**
     * 根据teamId查询team
     * @param teamId
     * @return
     */
    @InnerAuth
    @GetMapping("/queryInfoByTeamId/{teamId}")
    public R<SysTeam> queryInfoByTeamId(@PathVariable Long teamId){
        SysTeam team = sysTeamService.queryInfoByTeamId(teamId);
        return R.ok(team);
    }

    /**
     * 查询人员架构列表
     */
    @RequiresPermissions("sys:sysTeam:list")
    @PostMapping("/list")
    @Log(title = "sys", businessType = BusinessType.LIST)
    public AjaxResult list(@RequestBody ExportTeamVO vo, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
        //设置当前登录用户的部门Id，用于权限控制
        if (Objects.isNull(vo.getDeptId())) {
            vo.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        }
        Page<ExportTeamVO> list = sysTeamService.getPage(vo, page);
        return success(list);
    }

    /**
     * 导出人员架构列表 xlsx格式
     */
    //@Log(title = "人员架构", businessType = BusinessType.EXPORT)
    @RequiresPermissions("sys:sysTeam:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExportTeamVO vo) {
        //设置当前登录用户的部门Id，用于权限控制
        List<ExportTeamVO> list = getExportTeamVOList(vo);
        //将查询出来的list转为树结构
//        List<ExportTeamVO> list1 = sysTeamService.buildTreeList(response, "人员架构", list);
        ExcelUtil<ExportTeamVO> util = new ExcelUtil<ExportTeamVO>(ExportTeamVO.class);
        util.exportExcel(response, list, "人员架构数据");
    }

    private List<ExportTeamVO> getExportTeamVOList(ExportTeamVO vo) {
        //设置当前登录用户的部门Id，用于权限控制
        vo.setCurrDeptId(SecurityUtils.getLoginUser().getDeptId());
        return sysTeamService.getPageList(vo);
    }


    /**
     * 导出人员架构列表 xmind格式
     */
    //@Log(title = "人员架构", businessType = BusinessType.EXPORT)
    @RequiresPermissions("sys:sysTeam:export")
    @PostMapping("/exportXmind")
    public void exportXmind(HttpServletResponse response, ExportTeamVO vo) {
        List<ExportTeamVO> list = getExportTeamVOList(vo);
        //将查询出来的list转为树结构
        List<ExportTeamVO> treeList = TreeXmindlUtil.buildTreeList(list);
        //过滤所有有下级的数据导出
        List<ExportTeamVO> collectList = treeList.stream().filter(item -> item.getChild().size() > 0).collect(Collectors.toList());
        try {
            TreeXmindlUtil.createMindMap(collectList, "人员架构", response);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CoreException e) {
            e.printStackTrace();
        }
//        ExcelUtil<ExportTeamVO> util = new ExcelUtil<ExportTeamVO>(ExportTeamVO.class);
//        util.exportExcel(response, list, "人员架构数据");
    }

    /**
     * 获取人员架构详细信息
     */
    @RequiresPermissions("sys:sysTeam:query")
    @GetMapping(value = "/{teamId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult get(@PathVariable("teamId") Long teamId) {
        return success(sysTeamService.getById(teamId));
    }

    /**
     * 新增人员架构
     */
    @Log(title = "人员架构", businessType = BusinessType.INSERT)
    @RequiresPermissions("sys:sysTeam:add")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysTeamVO vo) {
        SysTeam sysTeam = new SysTeam();
        BeanUtils.copyPropsIgnoreNull(vo, sysTeam);

        sysTeam.setCreateBy(SecurityUtils.getUsername());
        return toAjax(sysTeamService.save(sysTeam));
    }

    /**
     * 修改人员架构
     */
    //@Log(title = "人员架构", businessType = BusinessType.UPDATE)
    @RequiresPermissions("sys:sysTeam:edit")
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SysTeamVO vo) {
        SysTeam sysTeam = new SysTeam();
        BeanUtils.copyPropsIgnoreNull(vo, sysTeam);
        return toAjax(sysTeamService.updateById(sysTeam));
    }

    /**
     * 删除人员架构
     */
    //@Log(title = "人员架构", businessType = BusinessType.DELETE)
    @RequiresPermissions("sys:sysTeam:remove")
	@DeleteMapping("/{teamIds}")
    public AjaxResult remove(@PathVariable Long[] teamIds) {
        return toAjax(sysTeamService.removeBatchByIds(Arrays.asList(teamIds)));
    }

    @Operation(summary = "新版评价-admin页面-左上方团队下拉列表")
//    @RequiresPermissions("@ss.hasPermi('sys:sysTeam:query')")
    @GetMapping(value = "/getTeamList")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getTeamList() {
        Boolean aBoolean = VerifyUtil.whetherAllPermissions();
        return success(sysTeamService.getTeamList(aBoolean));
    }


    /**
     * 解忧馆记录，查询当前登录用户下所有团队管理者
     */
//    @RequiresPermissions("@ss.hasPermi('sys:sysTeam:list')")
    @GetMapping("/getLeaderListByDeptId/{deptId}")
    @Log(title = "sys", businessType = BusinessType.LIST)
    public AjaxResult getLeaderListByUserId(@PathVariable Long deptId) {
        List<SysTeam> list = sysTeamService.getLeaderListBydeptId(deptId);
        return success(list);
    }


}
